package com.wetao.lib_common.common.ui;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.provider.Settings;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatTextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.R;
import com.wetao.lib_common.R2;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseListResponse;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.response.AppVersionInfo;
import com.wetao.lib_common.bean.response.GetSubjectList;
import com.wetao.lib_common.bean.response.Loginbean;
import com.wetao.lib_common.common.contract.LoginContract;
import com.wetao.lib_common.common.presenter.LoginPresenter;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.net.cookies.PersistentCookieStore;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.BaseEvent;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.ConstantUtils;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.InputUtils;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.view.dialog.CustomDialog;
import com.wetao.lib_common.view.dialog.OnCustomDialogItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 所有模块统一登录页面
 */
@Route(path = ConstantArouter.PATH_COMMON_LOGINACTIVITY)
public class Common_LoginActivity extends BaseActivity<LoginContract.View, LoginContract.Presenter> implements
        LoginContract.View {

    @Autowired
    String targetUrl;
    @BindView(R2.id.et_login_account)
    EditText account_edt;
    @BindView(R2.id.et_login_password)
    EditText password_edt;
    @BindView(R2.id.iv_eye)
    ImageView ivEye;
    @BindView(R2.id.iv_remmber)
    ImageView iv_remmber;
    @BindView(R2.id.btn_login)
    Button btnLogin;
    private boolean eyeOpen = false;
    private boolean isRemmeber = false;

    int mEnterSetNum = 0;

    private String[] dotText = {" . ", " . . ", " . . ."};
    ValueAnimator valueAnimator;




    @Override
    public int getLayoutId() {
        return R.layout.activity_common__login;
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }

    @Override
    public void setImmersionBar() {
        //hideBottomUIMenu();
        ImmersionBar.with(this).reset();
        ImmersionBar.with(this)
                .transparentBar()
                .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
                .init();
    }

    @Override
    public LoginContract.Presenter createPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    public LoginContract.View createView() {
        return this;
    }

    @Override
    public void init() {
        if(!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        InputUtils.setEditTextInhibitInputSpace(password_edt);

        account_edt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkSaveUser();
        getPresenter().getClientVersionInfo((HashMap<String, Object>) ComUtil.getHashmapByStr(
                new String[]{"version"},
                new Object[]{ConstantUtils.getAppVersionName()}), false, false);
    }


    private void checkSaveUser(){
        eyeOpen = false;
        password_edt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        String loginInfo = SPUtils.getInstance().getString(Constants.USER_ID_LIST,"");
        isRemmeber = SPUtils.getInstance().getBoolean(Constants.IS_REMMBER_PASSWORD, false);
        if (!TextUtils.isEmpty(loginInfo)){
            account_edt.setText(loginInfo.split("/")[0]);
            if(isRemmeber) {
                password_edt.setText(loginInfo.split("/")[1]);
            }
        }

        if(isRemmeber) {
            iv_remmber.setImageResource(R.drawable.common_login_select);
        } else {
            iv_remmber.setImageResource(R.drawable.common_login_select_n);
        }
    }

    @Override
    public void getLoginResult(BaseResponse<Loginbean> data) {

        //登录成功时
        //保存参数
        Loginbean loginbean = data.getData();
//        if(JsonUtils.isGoodJson(data.getData().toString())) {
//            LogUtils.i(data.getData().toString());
//            loginbean = JsonUtils.fromJson(data.getData().toString(), Loginbean.class);
//            LogUtils.i(loginbean.toString());
//        }
        if(loginbean == null) {
            ToastUtil.initToast("返回参数错误");
            if(valueAnimator != null && valueAnimator.isStarted()) {
                valueAnimator.cancel();
            }
            btnLogin.setText("登录");
            btnLogin.setEnabled(true);
            return;
        }



        PersistentCookieStore.getCookieStore().saveUserInfo(
                loginbean.getMobile(),
                password_edt.getText().toString().trim());
        SPUtils.getInstance().put(Constants.HEAD_XTOKEN, loginbean.getToken());
        SPUtils.getInstance().put(Constants.USER_ID_KEY, loginbean.getId().intValue() + "");
        SPUtils.getInstance().put(Constants.USER_ID_LIST,loginbean.getAccount().trim() + "/" + password_edt.getText().toString().trim());
        SPUtils.getInstance().put(Constants.USER_LOGIN_INFO,JsonUtils.toJson(loginbean));
        SPUtils.getInstance().put(Constants.USER_PEN_MAC,loginbean.getPenMac());
        DBUtils.getInstance(this).clear();
        DBUtils.getInstance(this).getDaoSession();


        getPresenter().getSubjectList(null
                , false, false);

        /*BaseEvent event = new BaseEvent();
        event.setCode(0);
        EventBus.getDefault().post(event);

        finish();*/
    }

    @Override
    public void getSubjectListResult(BaseListResponse<GetSubjectList> data) {
        if(valueAnimator != null && valueAnimator.isStarted()) {
            valueAnimator.cancel();
        }
        btnLogin.setText("登录");
        btnLogin.setEnabled(true);

        List<GetSubjectList> list = data.getData();
        if(list != null) {
            SPUtils.getInstance().put(Constants.GET_SUBJECT_LIST,JsonUtils.toJson(list));
            /*String str = SPUtils.getInstance().getString(Constants.GET_SUBJECT_LIST);
            List<GetSubjectList> list2 = JsonUtils.fromJsonList(str, new TypeToken<List<GetSubjectList>>() {}.getType());
            LogUtils.e("str -> " + str);
            LogUtils.e("list2 -> " + list2);*/

        }

        if(targetUrl != null){
            //跳转到目标页
            ARouter.getInstance().build(targetUrl)
                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                            |Intent.FLAG_ACTIVITY_NEW_TASK)
                    .navigation();
        }else {
            //ARouter.getInstance().build(ConstantArouter.PATH_APP_SPLASHACTIVITY).navigation();
            ARouter.getInstance().build(ConstantArouter.PATH_APP_HOMEACTIVITY)//指定跳到那个页面
                    .withString("fromPath", ConstantArouter.PATH_COMMON_LOGINACTIVITY)
                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                            |Intent.FLAG_ACTIVITY_NEW_TASK)
                    .navigation();
        }
    }

    @Override
    public void getSubjectListFail() {
        if(valueAnimator != null && valueAnimator.isStarted()) {
            valueAnimator.cancel();
        }
        btnLogin.setText("登录");
        btnLogin.setEnabled(true);
    }

    @Override
    public void getLoginError() {
        if(valueAnimator != null && valueAnimator.isStarted()) {
            valueAnimator.cancel();
        }
        btnLogin.setText("登录");
        btnLogin.setEnabled(true);
    }

    @Override
    public void getClientVersionResult(BaseResponse<AppVersionInfo> data) {
        if (null == data) return;
        LogUtils.i("getClientVersionResult data " + data.toString());
        AppVersionInfo appVersionInfo = data.getData();
        if (null != appVersionInfo) {
            if (!TextUtils.isEmpty(appVersionInfo.getDownloadUrl())) {
                showUpgradeDialog(appVersionInfo.getVersion(), ComUtil.getApkSize(appVersionInfo.getApkSize()),
                        appVersionInfo.getDescription(), appVersionInfo);
            }
        }
    }

    @Override
    public void getClientVersionError() {

    }


    @OnClick({
            R2.id.ll_remmber,
            R2.id.iv_eye,
            R2.id.btn_login,
            R2.id.tv_forget_pwd,
            R2.id.tv_register,
            R2.id.iv_logo
    })
    public void click(View view) {
        int id = view.getId();
        if(id == R.id.btn_login){
            String account = account_edt.getText().toString();
            String password = password_edt.getText().toString();
            if (account.isEmpty()) {
                ToastUtil.initToast("请输入手机号码");
                return;
            }
            if (password.isEmpty()) {
                ToastUtil.initToast("请输入密码");
                return;
            }
            if(!ComUtil.isNetworkAvailable(this)) {
                ToastUtil.initToast(getString(R.string.network_disconnect));
                return;
            }

            btnLogin.setText("登录中");
            btnLogin.setEnabled(false);
            if (valueAnimator == null) {
                valueAnimator = ValueAnimator.ofInt(0, 3).setDuration(1000);
                valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        int i = (int) animation.getAnimatedValue();
                        btnLogin.setText("登录中" + dotText[i % dotText.length]);
                    }
                });
            }
            if(valueAnimator != null) {
                valueAnimator.start();
            }


            getPresenter().getLogin(ComUtil.getHashmapByStr(
                    new String[]{"account", "password"},
                    new String[]{account.trim(), password.trim()})
                    , false, false);
        }else if(id == R.id.tv_register){
            //跳转到注册页 同意用arouter跳转，便于以后移动模块的改动
            ARouter.getInstance().build(ConstantArouter.PATH_COMMON_REGISTERACTIVITY)
                    .navigation();
            /*ARouter.getInstance().build(ConstantArouter.PATH_DEMOCYH_CYHMAINACTIVITY)
                    .navigation();*/
            /*ARouter.getInstance().build(ConstantArouter.PATH_MARKING_TRACKSYNCACTIVITY)
                    .navigation();*/
        }else if (id == R.id.tv_forget_pwd){
            ARouter.getInstance().build(ConstantArouter.PATH_COMMON_PWDRESETACTIVITY)
                    .withString("phone",account_edt.getText().toString())
                    .navigation();
        }else if(id == R.id.iv_eye) {
            eyeOpen = !eyeOpen;
            if(eyeOpen) {
                ivEye.setImageResource(R.drawable.common_login_eye_open);
                password_edt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                ivEye.setImageResource(R.drawable.common_login_eye_close);
                password_edt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
        } else if(id == R.id.ll_remmber) {
            isRemmeber = !isRemmeber;
            SPUtils.getInstance().put(Constants.IS_REMMBER_PASSWORD, isRemmeber);
            if(isRemmeber) {
                iv_remmber.setImageResource(R.drawable.common_login_select);
            } else {
                iv_remmber.setImageResource(R.drawable.common_login_select_n);
            }

        } else if(id == R.id.iv_logo) {
            mEnterSetNum++;
            if(mEnterSetNum == 5) {
                mEnterSetNum = 0;
                //Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                //startActivity(intent);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if(valueAnimator != null) {
            valueAnimator.cancel();
            valueAnimator = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEventReceived(BaseEvent event) {
        if(event.getCode() == 0){
            finish();
        }
    }


    private CustomDialog mCustomDialogUpgrade;

    private void showUpgradeDialog(String newVersion, String versionSize, String versionDes, AppVersionInfo versionInfo) {
        // if(null == mCustomDialogUpgrade)
        {
            mCustomDialogUpgrade = new CustomDialog(this,
                    R.layout.user_dialog_version_upgrade,
                    new int[]{R.id.ib_delete, R.id.bt_ok, R.id.tv_version_desc},
                    0,
                    false,
                    false,
                    Gravity.CENTER);
            mCustomDialogUpgrade.setOnDialogItemClickListener(new OnCustomDialogItemClickListener() {
                @Override
                public void OnCustomDialogItemClick(CustomDialog dialog, View view) {
                    int id = view.getId();
                    if (id == R.id.bt_ok) {
                        ARouter.getInstance().build(ConstantArouter.PATH_APP_UPDATEACTIVITY)
                                .withString("versionInfo", JsonUtils.toJson(versionInfo))
                                .navigation();
                    }
                }
            });
        }

        mCustomDialogUpgrade.setCancelable(false);

        mCustomDialogUpgrade.show();

        final List<View> viewList = mCustomDialogUpgrade.getViews();
        if (null != viewList) {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("版本: %s", newVersion)).append("\n");
            sb.append(String.format("大小: %s", versionSize)).append("\n");
            sb.append("更新内容:").append("\n");
            sb.append(versionDes);
            ((AppCompatTextView) viewList.get(2)).setText(sb.toString());

            viewList.get(0).setVisibility(View.INVISIBLE);
        }
    }
}
